/*
 * Copyright 2010, 2011 Matt Oliveri
 *
 * This file is part of JConfigGen
 *
 * JConfigGen is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JConfigGen is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JConfigGen.  If not, see <http://www.gnu.org/licenses/>.
 */

package atma.jconfiggen.sax;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import atma.jconfiggen.Expr;
import atma.jconfiggen.NewObj;

class LateNewH extends NewH
{
	private static final AttrMatcher consAttr = new AttrMatcher("constructor");

	private final String clss;
	private final String types;
	private final String id;
	private final String[] atts;

	LateNewH(SAXHandler s,ArrayList<Expr> p,String c,String t,String i,String[] a)
	{
		super(s,p);
		clss = c;
		types = t;
		id = i;
		atts = a;
	}

	final void setupNewO(ArrayList<Expr> args)
	{
		if (args == null) newo = new NewObj(saxh.config,clss,types,id,"");
		else newo = new NewObj(saxh.config,clss,types,id,args);
	}

	private void addSetters() {for (int i = 0;i < atts.length;i += 2) addSetter(atts[i],atts[i + 1]);}

	private void ensureSetup()
	{
		if (sub != null) return;
		if (newo == null) setupNewO(null);
		setupSub();
		addSetters();
	}

	ElemH elem(SAXHandler.Elem e,Attributes attr) throws SAXException
	{
		if (e == SAXHandler.Elem.CONSTRUCTOR)
		{
			if (newo != null) complain("A constructor element is only allowed as the first subelement.");
			consAttr.match(saxh.loc,attr);
			return new ConstructorH(this); // ConstructorH will call our setupNewO().
		}
		ensureSetup();
		return elemexp(e,attr);
	}

	ElemH elemstr(String tag,Attributes attr) throws SAXException
	{
		ensureSetup();
		return scall(tag,attr);
	}

	void end()
	{
		if (sub == null)
		{
			if (newo == null) setupNewO(null);
			if (atts.length > 0)
			{
				setupSub();
				addSetters();
				addPxRef();
			}
			else pnt.add(newo);
		}
		else addPxRef();
	}
}
